<?php

namespace app\index\controller;

use app\common\library\Auth;
use app\common\validate\MemberAvatarChangeValidate;
use app\common\validate\MemberPasswordChangeValidate;
use think\helper\Hash;
use think\Request;

class Member extends Base
{

    public function index()
    {
        return view();
    }

    public function showChangePasswordPage()
    {
        return view();
    }

    public function changePasswordHandler(Request $request)
    {
        $data = $request->only(['old_password', 'new_password', 'new_password_confirm']);
        $this->validator($data, MemberPasswordChangeValidate::class);

        $user = Auth::getInstance()->user();

        // 判断原密码是否正确
        if (! Hash::check($data['old_password'], $user->password)) {
            $this->error('原密码不正确');
        }

        $user->password = $data['new_password'];
        $user->save();

        $this->success('密码修改成功');
    }

    public function showAvatarChangePage()
    {
        return view();
    }

    public function avatarChangeHandler(Request $request)
    {
        $data = $request->file();
        $this->validator($data, MemberAvatarChangeValidate::class);

        $file = $data['file'];
        $info = $file->move('./public/uploads');
        $url = '/uploads/' . str_replace('\\', '/', $info->getSaveName());

        $user = app('auth')->user();
        $user->avatar = $url;
        $user->save();

        $this->success('头像修改成功');
    }

    public function showSentencesPage()
    {
        $sentences = app('auth')->user()->sentences()->order('create_time', 'desc')->paginate(10);
        return view('', compact('sentences'));
    }

    public function showSentencesCommentPage()
    {
        $comments = app('auth')->user()->comments()->order('create_time', 'desc')->paginate(10);
        return view('', compact('comments'));
    }

}
